package club.hicode.daydayup.lambda;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.github.jsonzou.jmockdata.JMockData;
import org.junit.Test;

import java.sql.SQLOutput;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toList;

/**
 * 测试 Lambda
 *
 * @author Liu Chunfu
 * @date 2018-04-26 下午5:24
 **/
public class LambdaTest {

    private List<Person> personList = new ArrayList<>();


    @Test
    public void test1() {
        for (int i = 0; i < 10; i++) {
            Person mock = JMockData.mock(Person.class);
            mock.setClassName(i % 2 + "");
            personList.add(mock);
        }

        Map<String, List<Person>> collect = personList.stream().collect(Collectors.groupingBy(Person::getClassName));
        String s = JSONUtil.toJsonPrettyStr(collect);
        System.out.println(s);
    }

    @Test
    public void testStream() {
        Stream<String> stream = Stream.generate(() -> RandomUtil.randomString(3));
        Optional<String> any = stream.findAny();
        System.out.println(any.get());
    }

    @Test
    public void test4() {
        List<Task> taskList = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            taskList.add(new Task(i + ""));
        }

        taskList.stream().parallel().forEach(x -> {
            System.out.println(x.getId());
            System.out.println(Thread.currentThread().getId());
            ThreadUtil.sleep(5, TimeUnit.SECONDS);
            System.out.println("---------");
        });
    }

    @Test
    public void test5() {
        List<Integer> numbers1 = Arrays.asList(1, 2, 3);
        List<Integer> numbers2 = Arrays.asList(3, 4);

        List<Stream<int[]>> collect = numbers1.stream().map(i -> numbers2.stream().map(j -> new int[]{i, j})).collect(Collectors.toList());


        List<int[]> pairs = numbers1.stream().flatMap(i -> numbers2.stream().map(j -> new int[]{i, j})).collect(toList());

        pairs.forEach(a -> System.out.println(a[0] + "-" + a[1]));

    }

    @Test
    public void test6() {
        String[] arrayOfWords = {"Goodbye", "World"};
        Stream<String> stream = Arrays.stream(arrayOfWords).map(x -> x.split("")).flatMap(Arrays::stream);
        stream.forEach(s -> System.out.println(s));
    }
}
